package com.ceba.test.modules.storage.filter;

import com.ceba.test.base.config.LogicPathUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class FileStorageFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)arg0;
		HttpServletResponse response=(HttpServletResponse)arg1;
		String url=request.getRequestURI();
		url=URLDecoder.decode(url,"UTF-8");
		String path= LogicPathUtil.getBrowserPathToAbsolutelyPath(url);
        File file = new File(path);
        ServletOutputStream outputStream=response.getOutputStream();
        if(file.exists()) {
			FileInputStream fileInputStream = new FileInputStream(file);
			Path pathType = Paths.get(path);
			response.addHeader("Content-Length", "" + file.length());
			response.addHeader("content-type", "" + Files.probeContentType(pathType));
			//将文件读入流
			IOUtils.copy(fileInputStream, outputStream);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
